↜ Back to index Introduction to Numerical Analysis 1

Part b—Lecture 8

Report 2 is assigned. Submit the solutions by August 6 (Friday) to LMS.

Allocatable arrays

So far we have been using arrays whose size is determined at the compile time. However, it is possible to set the size during runtime, for example based on users output. This is what Fortran’s allocatable arrays are for.

implicit none
real, dimension(:), allocatable :: x, y
integer n, i

! we cannot use arrays x, y yet since it is not allocated

print *, 'Enter array size'
read *, n

! allocate the memory for n elements
allocate(x(n))
! allocate the memory for n + 1 elements
allocate(y(0:n))

! now we can start using x as any other array with elements x(1), x(2), ..., x(n)
do i = 1, n
    x(i) = i
enddo

print *, x

do i = 0, n
    y(i) = i
enddo

print *, y

end

This is how we can modify the code for the heat equation using allocatable arrays.

implicit none
real, parameter :: pi = 4. * atan(1.)
integer n, k, nmax, M
real h, tau, x
real, dimension(:), allocatable :: u, v

read *, M

allocate(u(0:M))
allocate(v(0:M))

h = 1. / M
tau = h * h / 4.
nmax = 0.25 / tau

do k=0, M
    x = k * h
    u(k) = sin(pi * x)
end do
 call printstep(0., u)

do n=0, nmax-1
    v(0) = u(0) ! boundary condition is constant in time
    do k = 1, M-1
        v(k) = u(k) + (tau / (h * h)) * (u(k - 1) - 2 * u(k) + u(k + 1))
    end do
    v(M) = u(M) ! boundary condition is constant in time

    call printstep((n+1) * tau, v)

    u = v
end do
 contains
    subroutine printstep(tn, un)
        real tn
        real, dimension(:), allocatable :: un
        integer k
        do k = 0, M
            print *, tn, k * h, un(k)
        end do
        print *
    end subroutine
end